//
//  SoundWaveController.m
//  SoundWave
//
//  Created by 朱帅 on 2017/3/6.
//  Copyright © 2017年 Zs. All rights reserved.
//

#import "SoundWaveController.h"
#import "SoundWaveView.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface SoundWaveController ()<AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, strong) SoundWaveView *waveView;

@end

@implementation SoundWaveController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"back" style:UIBarButtonItemStylePlain target:self action:@selector(backAndDestroy)];
    [self setPlayer];
    [self setUI];
}

- (void)setUI
{
    self.view.backgroundColor = [UIColor blackColor];
    _waveView = [[SoundWaveView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds)/2 - 25, CGRectGetWidth(self.view.bounds), 50)];
    __block AVAudioPlayer *player = self.player;
    _waveView.levelCallback = ^(SoundWaveView * waver) {
        [player updateMeters];
        CGFloat level = pow (10, ([player averagePowerForChannel:0]+[player averagePowerForChannel:1])/ 2 / 40.f);
        waver.level = level;
    };
    [self.view addSubview:_waveView];
}

- (void)setPlayer
{
    NSString *path = [[NSBundle mainBundle]pathForResource:self.songName ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.player.delegate = self;
    self.player.meteringEnabled =YES;
    [self.player play];
}

- (void)backAndDestroy
{
    [self.player stop];
    self.player = nil;
    self.player.delegate = nil;
    [_waveView.displayLink invalidate];
    _waveView.displayLink = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
